package com.cyyang.shop.controller;

import java.io.File;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cyyang.shop.bean.Brand;
import com.cyyang.shop.service.BrandService;
import com.github.pagehelper.PageInfo;


@Controller
@RequestMapping("/brand")
public class BrandController {
	
	@Value("${uploadPath}")
	private String uploadPath;
	
	
	@Reference
	BrandService brandService;
	
	@RequestMapping("list")
	public String list(HttpServletRequest req,@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = "6") Integer pageSize,Brand brand) {
		PageInfo<Brand> info = brandService.findBrand(pageNum, pageSize, brand);
		req.setAttribute("info", info);
		List<Brand> list = info.getList();
		return "/brand/brand_list";
	}
	
	@RequestMapping("toAdd")
	public String toAdd() {
		return "brand/addBrand";
	}
	
	@RequestMapping("add")
	@ResponseBody
	public boolean add(Brand b,MultipartFile filePic) {
		try {
			System.out.println(b);
			String path = upload(filePic);
			b.setPicPath(path);
			brandService.addBrand(b);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private String upload(MultipartFile filePic) {
		String string=null;
		if(filePic!=null && !filePic.isEmpty()) {
			string = filePic.getOriginalFilename();
			string=UUID.randomUUID()+string;
			File file = new File(uploadPath,string);
			try {
				filePic.transferTo(file);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return string;
	}
	
	
	

}
